<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>可编辑文件列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="${base}/css/bootstrap.css">
<script type="text/javascript" src="${base}/js/jquery-3.1.0.js"></script>
<script type="text/javascript" src="${base}/js/bootstrap.js"></script>
<script>
		$(function(){
		/* 	$("#tableName").blur(function(){
				var tableName = $(this).val();
				
				if(tableName != ""){
					$.post("${ pageContext.request.contextPath }/table/checkTableName",{"tableName":tableName},function(data){
		 				if(data == 1){
		 					$("#s1").html("<font color='green'>该表格名可以使用</font>");
		 					$("#saveTable").attr("disabled",false);
		 				}else if(data == 2){
		 					$("#s1").html("<font color='red'>该表格名已经存在</font>");
		 					$("#saveTable").attr("disabled",true);
	 	 				}
	 	 			});
	 			}else{
	 				$("#s1").html("<font color='red'>表格名不能为空</font>");
	 				$("#saveTable").attr("disabled",true);
	 			}
	 		});
			 */
			$("#tableName").keyup(function(){
				var tableName = $(this).val();
				
				if(tableName != ""){
					$.post("${ pageContext.request.contextPath }/table/checkTableName",{"tableName":tableName},function(data){
		 				if(data == 1){
		 					$("#s1").html("<font color='green'>该表格名可以使用</font>");
		 					$("#saveTable").attr("disabled",false);
		 				}else if(data == 2){
		 					$("#s1").html("<font color='red'>该表格名已经存在</font>");
		 					$("#saveTable").attr("disabled",true);
	 	 				}
	 	 			});
	 			}else{
	 				$("#s1").html("<font color='red'>表格名不能为空</font>");
	 				$("#saveTable").attr("disabled",true);
	 			}
	 		});
	 		
	 	});
			
</script>
</head>

<body>	
	<!--整体div-->
	<div class="container">
		<jsp:include page="${path}/menu.jsp"></jsp:include>
		<div style="margin-left: 20px;margin-bottom: 10px; color: grey">当前位置：模板管理 > ${template.templateName}</div>
		
		<div >
			<input type="button" class="btn btn-primary"
				value="${template.templateName}">
		</div>
		<div class="span12" style="padding-top: 20px; padding-bottom: 20px">
					<font size="3" style="width: 300px;">模板描述：${template.templateDesc }</font>
				</div>
		<div style="overflow-x: scroll; width: 100%; white-space: nowrap;">
			<!-- alan_18.3.2_start_update_style -->
			<!-- <table class="table table-condensed table table-bordered" -->
			<table class="table table-striped table-bordered table-hover dataTables-example"
				style="width: 100%; height: auto;  overflow: auto;" border="1"
				id="table">
				<tbody id="tbody">
					<tr style="height: 40px">
						<c:forEach items="${templateColList}" var="templateCol">
							<td  style="width: 120px;" >
							<%-- <button type="text" value="${templateCol.colName}" readonly="readonly" style="border: none; height: 35px; font-size: 10px; width: 100%; word-wrap: break-word;">${templateCol.colName}</button>
							 --%><input type="text" value="${templateCol.colName}" readonly="readonly" style="border: none; height: 35px; font-size: 10px; width: 100%; word-wrap: break-word;">
							</td>
						</c:forEach>
					</tr>
				
				
					<c:forEach begin="1" end="5" step="1" >
						<tr class="tr" style="height: 40px">

							<c:forEach items="${templateColList}" var="templateCol">
								<c:if test="${templateCol.colType==0}">
									<td>
									<input type="text" value="${templateCol.defVal}" readonly="readonly" style="border: none; height: 35px; font-size: 10px; width: 100%; word-wrap: break-word;">
									</td>
								</c:if>
								<c:if test="${templateCol.colType==1}">
									<c:set value="${ fn:split(templateCol.defVal, '||') }" var="val" />
									<%-- <td><select style="width: 100px; height: 25px;">
											<c:forEach items="${val}" var="v">
												<option>${v}</option>
											</c:forEach>
									</select></td> --%>
									
									<td class="td" ><select
										style="width: 100%; height: 30px;background:${fn:substring(val[0],fn:indexOf(val[0],'#'),fn:length(val[0]))} " >
											<c:forEach items="${val}" var="va">
											
												<option class="${fn:substring(va,fn:indexOf(va,'#'),fn:length(va))}">
												${fn:substring(va,0,fn:indexOf(va,'#'))}
												</option>
											</c:forEach>
									</select></td>
								</c:if>
							</c:forEach>
						</tr>
					</c:forEach>
				</tbody>
			</table>
			<!-- alan_18.3.2_end_update_style -->
		</div>
		<!-- <button type="button" class="btn btn-primary"
			onclick="AddRow(document.getElementById('table'),1)">增加一行</button> -->
		<%-- <a
			href="${pageContext.request.contextPath}/tpl/toTable?templateId=${template.id}&projectId=${project.id}">
			<input type="button" class="btn btn-primary" value="生成表格">
		</a> --%>

			<c:if test="${project.managerName == user.name}">

			<button class="btn btn-primary" data-toggle="modal"
				data-target="#myModal">生成表格</button>
			<!--  定义模态框触发器，此处为按钮触发  -->
			<button class="btn btn-primary" data-toggle="modal"
				data-target="#myModal1">编辑模板描述</button>
			<!--  定义模态框触发器，此处为按钮触发  -->
			</c:if>

			<form method="post" action="${pageContext.request.contextPath}/tpl/toTable?templateId=${template.id}&projectId=${project.id}&userId=${user.id}" class="form-horizontal" role="form"
				id="toTableForm" onsubmit="return ">
				<div class="modal fade" id="myModal" role="dialog" tabindex=-1
					aria-labelledby="myModalLabel" aria-hidden="true">
					<!--  定义模态框，过渡效果为淡入，id为myModal,tabindex=-1可以禁用使用tab切换，aria-labelledby用于引用模态框的标题，aria-hidden=true保持模态框在触发前窗口不可见  -->
					<div class="modal-dialog">
						<!--  显示模态框对话框模型（若不写下一个div则没有颜色）  -->
						<div class="modal-content">
							<!--  显示模态框白色背景，所有内容都写在这个div里面  -->

							<div class="btn-info modal-header">
								<!--  模态框标题  -->
								<button type="button" class="close" data-dismiss="modal">&times;</button>
								<!--  关闭按钮  -->
								<h4>添加表格</h4>
								<!--  标题内容  -->
							</div>

							<div class="modal-body">
								<!--  模态框内容，我在此处添加一个表单 -->
								<form class="form-horizontal" role="form">
									<div class="form-group">
										<label for="tableName" class="col-sm-3 control-label">表格名称：</label>
										<div class="col-sm-5">
											<input type="text" id="tableName" name="tableName" class="form-control well" placeholder="请输入表格名" />
												
										</div>
										<span id="s1"></span>
									</div>
									
								</form>
							</div>

							<div class="modal-footer">
								<!--  模态框底部样式，一般是提交或者确定按钮 -->
								<input type="button" onclick="toTable()" class="btn btn-info" value="确定">
								<button type="button" class="btn btn-default"
									data-dismiss="modal">取消</button>
							</div>

						</div>
						<!-- /.modal-content -->
					</div>
				</div>
				<!-- /.modal -->
			</form>
			
				<form method="post" action="" class="form-horizontal" role="form"
							id="myForm1" onsubmit="return ">
							<div class="modal fade" id="myModal1" role="dialog" tabindex=-1
								aria-labelledby="myModalLabel" aria-hidden="true">
								<!--  定义模态框，过渡效果为淡入，id为myModal,tabindex=-1可以禁用使用tab切换，aria-labelledby用于引用模态框的标题，aria-hidden=true保持模态框在触发前窗口不可见  -->
								<div class="modal-dialog">
									<!--  显示模态框对话框模型（若不写下一个div则没有颜色）  -->
									<div class="modal-content">
										<!--  显示模态框白色背景，所有内容都写在这个div里面  -->

										<div class="btn-info modal-header">
											<!--  模态框标题  -->
											<button type="button" class="close" data-dismiss="modal">&times;</button>
											<!--  关闭按钮  -->
											<h4>添加成员</h4>
											<!--  标题内容  -->
										</div>

										<div class="modal-body">
											<!--  模态框内容，我在此处添加一个表单 -->
											<form class="form-horizontal" role="form">
												<div class="form-group">
													<label for="templateDesc" class="col-sm-2 control-label">模板描述:</label>
													<div class="col-sm-6">
														<input type="hidden" name="templateId" value="${template.id }"/>
														
														<input type="text" id="templateDesc" name="templateDesc"
															class="form-control well" placeholder="请用一句话描述该模板" />
													</div>
												</div>

											</form>
										</div>

										<div class="modal-footer">
											<!--  模态框底部样式，一般是提交或者确定按钮 -->
											<button  class="btn btn-info" onclick="addTemplateDesc()" >确定</button>
											<button type="button" class="btn btn-default"
												data-dismiss="modal">取消</button>
										</div>

									</div>
									<!-- /.modal-content -->
								</div>
							</div>
							<!-- /.modal -->
						</form>
		


	</div>
</body>
<script type="text/javascript">

	function addTemplateDesc(){
		alert(11);
		$.ajax({  
	        type: "POST",  
	        url:"${ pageContext.request.contextPath }/tpl/addTemplateDesc",  
	        data:$('#myForm1').serialize(),// 序列化表单值  
	        dataType: "json",
	        success: function (data) {
	            location.reload();
	           
			},
			async: true,
			cache: false
			}); 
	   
	}
	
	function toTable(){
		
		var projectId = ${project.id};
		if(projectId != null || projectId != ""){
			
		var templateId = ${template.id};
		var userId = ${user.id};
		var tableName = $("#tableName").val();
		
		var map = {};

		var rows = table.rows.length;
		
		var cells = table.rows.item(0).cells.length;
		alert($(table.rows.item(0).cells.item(0).childNodes[1]).val());
		/*  for (var i = 0; i < 2; i++){
		alert($(table.rows.item(0).cells.item(0).childNodes[i]).val());
		}  */
		for (var i = 0; i < rows; i++) {
			var cellValue = [];
			for (var j = 0; j < cells; j++) {
				
				var valuej = table.rows.item(i).cells.item(j);
				
				if(i == 0){
					
				cellValue[j] = $(valuej.childNodes[1]).val();
				}else{
					cellValue[j] = $(valuej.childNodes[0]).val();
				}
				 
			}
			
			map[i.toString()] = cellValue;
		}
		var json = JSON.stringify(map);
		var params = JSON.stringify(json);
		alert(params);
		
		var lll="${ pageContext.request.contextPath }/excel/save";
		
	
		
		   var userId = ${user.id};
		console.log("tableName="+tableName+",userId="+userId);
	 $.ajax({
			url : lll,
			data : {
				"json" : params,
				"tableName" : tableName
			},
			type : "POST",
			success : function() {
				
			},
			async : true,
			cache : false
		});
		
		
		 $.ajax({  
	        type: "POST",  
	        url:"${ pageContext.request.contextPath }/tpl/toTable?templateId="+ templateId+"&projectId="+ projectId+"&userId="+userId,  
	        data:$('#toTableForm').serialize(),// 序列化表单值  
	        dataType: "json",
	        success: function (data) {
	           
	            window.location.href="${ pageContext.request.contextPath }/excel/editTable?tableName="+tableName+"&tableId="+data+"&userId="+userId+"&projectId="+projectId;
			},
			async: true,
			cache: false
			});  
		}else{
			alert("请先选择一个项目~");
		}
		
	}
	
	
	
	function showExcel(obj) {
		var filename = obj.value;
		var param = "filename=" + filename;
		console.log(filename);
		$
				.ajax({
					url : "${base}/excel/show",
					data : param,
					dataType : "json",
					type : "POST",
					success : function(data) {
						/*  $('#myModal').modal('show'); */
						var table = [];
						table
								.push('<table class="table table-condensed table table-bordered" style="width:1100px ;height:auto;border:1px solid;"  id="table"><tbody id="tbody">');
						$
								.each(
										data,
										function(index, tr) {
											table
													.push('<tr class="tr" style="height: 30px;width: 50px">');
											$
													.each(
															tr,
															function(index, td) {
																table
																		.push('<td class="td" style="width:50px";height:auto;"><input onchange=\"readHtml()\" type="text" style="border:none;height:35px;font-size: 10px;width:auto;word-wrap:break-word;" value='
																				+ td
																				+ ' ></td>');
															});
											table.push('</tr>');
										});
						table
								.push('<input type="hidden" value='+filename+' id="filename" ></input>');
						document.getElementById('table-body').innerHTML = table
								.join('');
					},
					async : true,
					cache : false
				});
	}
	function AddRow(table, index) {
		var lastRow = table.rows[table.rows.length - 1];
		alert(lastRow);
		var newRow = lastRow.cloneNode(true);
		table.tBodies[0].appendChild(newRow);

		return newRow;

	}

	function addRow() {
		var tr = document.createElement('tr');
		tr.className = "tr";
		var tbody = document.getElementById("tbody");
		var rows = table.rows.length;
		var cells = table.rows.item(0).cells.length;
		tbody.appendChild(tr);
		for (var i = 0; i < cells; i++) {
			var inputi = document.createElement('input');
			inputi.style.border = "none";
			inputi.style.height = "46px";
			inputi.style.font.size = "10px";
			var tdi = document.createElement('td');
			tdi.appendChild(inputi);
			tdi.className = "td";
			tdi.style.height = "46px";
			tdi.style.width = " 5%";
			tr.appendChild(tdi);
		}
	}
	function addCell() {
		$(".tr")
				.append(
						'<td style="height:30px;width:5%"class="td"><input type="text" style="border:none;height:46px;font-size:10px"></td>');
	}
	function readHtml() {
		var map = {};
		var rows = table.rows.length;
		var cells = table.rows.item(0).cells.length;
		for (var i = 0; i < rows; i++) {
			var cellValue = [];
			for (var j = 0; j < cells; j++) {
				valuej = table.rows.item(i).cells.item(j).childNodes[0].value;
				cellValue[j] = valuej;
			}
			map[i.toString()] = cellValue;
		}
		var json = JSON.stringify(map);
		var params = JSON.stringify(json);

		var filename = $("#filename").val();
		console.log(filename);
		$.ajax({
			url : "${base}/tpl/write",
			data : {
				"json" : params,
				"filename" : filename
			},
			type : "POST",
			success : function() {
				alert("更新成功");
			},
			async : true,
			cache : false
		});
	}
	function deleteExcel(obj) {
		var filename = obj.value;
		var param = "filename=" + filename;
		if (confirm("确认删除" + filename + "吗？")) {
			$.ajax({
				url : "${base}/excel/delete",
				data : param,
				dataType : "json",
				type : "POST",
				success : function(data) {
					//Location.href = "${base}/excel/list";
					alert("删除成功");
					location.reload();
				},
				async : true,
				cache : false
			});
		}
	}
	$(".tr").bind("mouseover", function() {
		$(this).css("background-color", "#eeeeee");
	})
	$(".tr").bind("mouseout", function() {
		$(this).css("background-color", "#ffffff");
	})
</script>
</html>


